"""A sample Velocitas vehicle app for adjusting seat position."""

import json
import logging

from vehicle import Vehicle  # type: ignore

from sdv.util.log import (  # type: ignore
    get_opentelemetry_log_factory,
    get_opentelemetry_log_format,
)

from sdv.vehicle_app import VehicleApp, subscribe_topic

logging.setLogRecordFactory(get_opentelemetry_log_factory())
logging.basicConfig(format=get_opentelemetry_log_format())
logging.getLogger().setLevel("DEBUG")
logger = logging.getLogger(__name__)


class WiperControlApp(VehicleApp):

    def __init__(self, vehicle_client: Vehicle):
        super().__init__()
        self.Vehicle = vehicle_client

    async def on_start(self):
        """Run when the vehicle app starts"""
        logger.info("app run on_start function")

    @subscribe_topic("wipercontrol/setMode/request")
    async def on_set_position_request_received(self, data_str: str) -> None:
        data = json.loads(data_str)
        response_topic = "wipercontrol/setMode/response"
        data_wiper_value = (await
                            self.Vehicle.Body.Windshield.Front.Wiping.Mode.get()).value
        status = data["status"]
        if status not in ["OFF", "SLOW", "MEDIUM", "FAST"]:
            await self.publish_event(
                response_topic,
                json.dumps(
                    {
                        "result": {
                            "status": 0,
                            "message": "invalid parameter values"
                        },
                    }
                )
            )
        else:
            if data_wiper_value == status:
                await self.publish_event(
                    response_topic,
                    json.dumps(
                        {
                            "result": {
                                "status": 0,
                                "message": f"wiper state has already {status}"
                            },
                        }
                    )
                )
            else:
                await self.Vehicle.Body.Windshield.Front.Wiping.Mode.set(status)
                await self.publish_event(
                    response_topic,
                    json.dumps(
                        {
                            "result": {
                                "status": 0,
                                "message": f"wiper state change to {status}"
                            },
                        }
                    )
                )
